package com.beans;

import java.io.IOException;
import java.io.Serializable;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import model.User;

import com.Constants;
import com.factory.Util;
import com.services.UserService;

@ManagedBean(name = "loginBean")
@RequestScoped
/**
 * 
 * @author kaloyan
 */
public class LoginBean implements Serializable {

	@EJB
	UserService service;

	@ManagedProperty(value = "#{UserSessionBean}")
	private UserSessionBean userSessionBean;

	public UserSessionBean getUserSessionBean() {
		return userSessionBean;
	}

	public void setUserSessionBean(UserSessionBean testBean) {
		this.userSessionBean = testBean;
	}

	private static final long serialVersionUID = 1L;
	private String password;
	private String message, uname;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public void loginProject() throws IOException {
		User user = service.authenticate(uname, password);
		if (user != null) {

			this.userSessionBean.setUser(user);

			// get Http Session and store username
			HttpSession session = Util.getSession();
			session.setAttribute(Constants.USERNAME, user.getUserName());

			session.setAttribute(Constants.USER_ID, user.getId());

			FacesContext.getCurrentInstance().getExternalContext()
					.redirect("home.seam");

			// return "home";
		} else {

			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN,
							"Invalid Login!", "Please Try Again!"));

			// invalidate session, and redirect to other pages

			// message = "Invalid Login. Please Try Again!";
			// return null;
		}
	}

	public String logout() {
		HttpSession session = Util.getSession();
		session.invalidate();
		return "start-page";
	}
}